import { Component, useEffect, useMemo, useState } from "react";
import { Dialog } from "@nutui/nutui-react-taro";
import styles from "./index.scss";
import { useModel } from "@/store";
import Taro, { useRouter } from "@tarojs/taro";
import { Tabs } from "@nutui/nutui-react-taro";
import { formatDate, calculateTime } from "@/utils/repeated";
import {
  queryScheduleInfo,
  payClinicReg,
  queryScheduleTimeInfo,
  queryAutoRcptNo,
  lockScheduleTime,
  unlockScheduleTime,
} from "@/services/register";
import Layout from "@/components/Layout";

// function getWeekday(date) {
//   const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
//   const weekday = new Date(date).getDay();
//   return weekdays[weekday];
// }

function getWeekday(dateString) {
  const date = new Date(dateString);
  const weekdays = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  return weekdays[date.getDay()];
}

// 示例：获取2024年5月19日是星期几
// console.log(getWeekday('2024-05-19'));

export default () => {
  const { params } = useRouter();
  const { curPatientInfo } = useModel("patient");

  const [tab5value, setTab5value] = useState("0");
  const [scheduleData, setScheduleData] = useState({});
  const { deptCode, deptName } = params;
  const startDate = formatDate(new Date(), "yyyy-MM-dd");
  const endDate = calculateTime(7);

  // 获取未来7天的日期
  const dayList = useMemo(() => {
    const today = new Date();
    return Array.from({ length: 7 }, (_, i) => {
      const futureDate = new Date(today);
      futureDate.setDate(today.getDate() + i);
      // const date = formatDate(futureDate, "MM·dd");
      return {
        title: i === 0 ? "今天" : formatDate(futureDate, "MM·dd"),
        key: formatDate(futureDate, "yyyy-MM-dd"),
      };
      // futureDate.toLocaleDateString();
    });
  }, []);

  useEffect(() => {
    if (deptCode) {
      queryScheduleInfo({ deptCode, startDate, endDate }).then((res) => {
        if (res) {
          // 按日期分组
          const groupedArr = res.reduce((acc, obj) => {
            var key = obj.clinicDate; // 选取要分组的属性（这里为age）作为key

            if (!acc[key]) {
              acc[key] = []; // 如果该key不存在于结果集合中，则创建新的空数组
            }

            acc[key].push(obj); // 将当前对象添加到相应的分组数组中

            return acc;
          }, {});
          setScheduleData(groupedArr);
        }
      });
    }
  }, [deptCode]);

  const onPayClinicReg = (item) => {
    Dialog.open("registerInfo", {
      title: "请确认预约信息",
      confirmText: "确认预约",
      content: (
        <view
          style={{
            fontSize: "32rpx",
            display: "flex",
            flexDirection: "column",
            gap: "20rpx",
          }}
        >
          <view>预约科室：{item.clinicDeptName}</view>
          <view>预约医生：{item.doctorName}</view>
          <view>就诊时间：{formatDate(item.clinicDate, "MM·dd")}</view>
        </view>
      ),
      onConfirm: async () => {
        // 请求分时信息
        const scheduleTimeInfo = await queryScheduleTimeInfo({
          clinicDate: formatDate(item.clinicDate, "yyyy-MM-dd"),
          clinicLabel: item.clinicLabel,
          timeDesc: item.timeDesc,
        });

        const serialNo = scheduleTimeInfo[0]?.serialNo;
        // 获取流水号
        const autoRcptNo = await queryAutoRcptNo({ userCode: "weixin" });
        // // 号源锁定
        const lockNo = await lockScheduleTime({
          clinicDate: formatDate(item.clinicDate, "yyyy-MM-dd"),
          clinicLabel: item.clinicLabel,
          timeDesc: item.timeDesc,
          serialNo: serialNo,
        });

        const paramData = {
          autoRcptNo: autoRcptNo.autoRcptNo,
          patientId: curPatientInfo.patientId,
          insuranceType: "101",
          chargeType: "01",
          clinicType: item.clinicType,
          clinicLabel: item.clinicLabel,
          visitDept: item.clinicDept,
          doctor: item.doctor,
          // payWay: "",
          operator: "weixin",
          timeDesc: item.timeDesc,
          serialNo: serialNo.toString(),
          povertyAttr: "0",
          visitDate: item.clinicDate,
          dataSource: "13",
        };

        payClinicReg(paramData)
          .then((res) => {
            Taro.showModal({
              title: "挂号成功",
              content: `请您于${formatDate(
                item.clinicDate,
                "yyyy年MM月dd日"
              )}(${getWeekday(item.clinicDate)})到${item.clinicDeptName}${
                item.clinicPosition
              }就诊`,
              showCancel: false,
              success: function(res) {
                if (res.confirm) {
                  Taro.reLaunch({
                    url: "/pages/index/index",
                  });
                  console.log("用户点击确定");
                } else if (res.cancel) {
                  console.log("用户点击取消");
                }
              },
            });
          })
          .catch(() => {
            Taro.showModal({
              title: "挂号失败",
              // content: '这是一个模态弹窗',
              showCancel: false,
              success: function(res) {
                // if (res.confirm) {
                //   Taro.reLaunch({
                //     url: "/pages/register/index/index",
                //   });
                //   console.log("用户点击确定");
                // } else if (res.cancel) {
                //   console.log("用户点击取消");
                // }
              },
            });
            unlockScheduleTime({ lockNo: lockNo.lockNo });
          });
      },
      onCancel: () => {
        Dialog.close("registerInfo");
      },
    });
  };

  return (
    <Layout title="选择日期">
      <view className={styles.selectdepWarp}>
        <view className={styles.top}>{deptName}</view>
        <view className={styles.content}>
          <Tabs
            style={{ height: "100%" }}
            value={tab5value}
            onChange={(value) => {
              setTab5value(value);
            }}
          >
            {dayList.map((item) => {
              return (
                <Tabs.TabPane key={item.key} title={item.title}>
                  {/* <Seconddep></Seconddep> */}

                  {scheduleData[item.key]?.map((x) => {
                    return (
                      <view
                        className={styles.scheduleCard}
                        onClick={() => {
                          onPayClinicReg(x);
                        }}
                      >
                        <view className={styles.cardtop}>
                          <view className={styles.doctorName}>
                            {x.doctorName}
                          </view>
                          <view className={styles.clinicType}>
                            {" "}
                            {x.clinicType}
                          </view>
                        </view>

                        <view className={styles.cardbottom}>
                          <view className={styles.time}>
                            {x.clinicDate} {x.timeDesc}
                          </view>
                          <view className={styles.num}>
                            余号{x.leftNum} /总号
                            {x.scheduleNum}
                          </view>
                        </view>
                      </view>
                    );
                  })}
                </Tabs.TabPane>
              );
            })}
          </Tabs>
        </view>
        <Dialog
          id="registerInfo"
          style={{
            "--nutui-dialog-header-font-size": "36rpx",
            "--nutui-button-default-font-size": "32rpx",
            "--nutui-button-default-background-color": "#ffffff",
          }}
        />
      </view>
    </Layout>
  );
};
